package com.zenghus.spring.formework.webmvc;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zenghu
 * @date 2018/5/1 16:12
 */
//设计这个类的主要目的是
// 1.将一个静态文件变成一个动态文件
// 2.根据用户返回的参数，返回一个动态的结果
// 3.最终输出一个字符串，交给resp输出
public class ViewResolver {
    private String viewName;
    private File templateFile;

    public ViewResolver(String viewName, File template) {
        this.viewName=viewName;
        this.templateFile=template;
    }

    public String viewResolver(ModelAndView modelAndView) throws IOException {
        StringBuffer sb=new StringBuffer();
        RandomAccessFile ra=new RandomAccessFile(this.templateFile,"r");
        String line=null;
        while (null!=(line=ra.readLine())){
            line = new String(line.getBytes("ISO-8859-1"), "utf-8");
            Matcher m=matcher(line);
            while (m.find()){
                for (int i=1;i<=m.groupCount();i++){
                    //要把定义的转义符号替换用户的值
                    String param=m.group(i);
                    Object paramValue= modelAndView.getModel().get(param);
                    if(paramValue==null){
                        continue;
                    }
                    line = line.replaceAll("￥\\{" + param + "\\}", paramValue.toString());
                    line = new String(line.getBytes("utf-8"), "ISO-8859-1");
                }
            }
            sb.append(line);
        }
        return sb.toString();
    }

    public static Matcher matcher(String str){
        Pattern pattern = Pattern.compile("￥\\{(.+?)\\}",Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return  matcher;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String line="asdf";
        line = new String(line.getBytes("ISO-8859-1"), "utf-8");
        Matcher m=matcher("￥{name}<br>");
        while (m.find()){
            for (int i=1;i<m.groupCount();i++){
                //要把定义的转义符号替换用户的值
                String param=m.group(i);
                Object paramValue= "zenghu";
                if(paramValue==null){
                    continue;
                }
                line=line.replaceAll("￥\\{"+param+"\\}",paramValue.toString());
            }
        }
        System.out.println(line);
    }

    public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }

    public File getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFile(File templateFile) {
        this.templateFile = templateFile;
    }
}